const api = require('../../utils/api.js');
const storage = require('../../utils/storage.js');
const imageUtil = require('../../utils/image.js');

Page({
  data: {
    statusBarHeight: 0,
    navBarHeight: 0,
    contentTop: 0,
    replyList: [], // 回复列表
    loading: false,
    currentUserId: 0,
    currentPage: 1,
    pageSize: 20,
    hasMore: true,
    totalCount: 0
  },

  onLoad(options) {
    console.log('💬 =============== 活动消息回复页面加载 ===============');
    
    // 获取系统状态栏高度
    const windowInfo = wx.getWindowInfo();
    const statusBarHeight = windowInfo.statusBarHeight;
    const navBarHeight = statusBarHeight + 44;
    const contentTop = navBarHeight;
    
    this.setData({
      statusBarHeight: statusBarHeight,
      navBarHeight: navBarHeight,
      contentTop: contentTop
    });
    
    // 获取当前用户ID
    this.getCurrentUserId();
    
    // 加载回复列表
    this.loadReplyList();
  },

  // 获取当前用户ID
  getCurrentUserId() {
    const userInfo = storage.getUserInfo();
    if (userInfo && userInfo.userid) {
      this.setData({
        currentUserId: userInfo.userid
      });
      console.log('👤 当前用户ID:', userInfo.userid);
    } else {
      console.error('❌ 未找到用户信息，请先登录');
      wx.showModal({
        title: '提示',
        content: '请先登录',
        success: (res) => {
          if (res.confirm) {
            wx.reLaunch({
              url: '/pages/login/index'
            });
          }
        }
      });
    }
  },

  // 🚀 加载回复列表
  loadReplyList(isPullDown = false) {
    if (this.data.loading) {
      console.log('⚠️ 正在加载中，忽略重复请求');
      return;
    }

    console.log('🔄 =============== 开始加载活动回复列表 ===============');
    
    if (!this.data.currentUserId) {
      console.error('❌ 用户ID无效');
      wx.showToast({
        title: '用户信息无效',
        icon: 'none'
      });
      return;
    }

    const that = this;
    
    // 如果是下拉刷新，重置页码
    if (isPullDown) {
      this.setData({
        currentPage: 1,
        hasMore: true
      });
    }

    this.setData({ loading: true });

    // 调用API查询回复列表
    api.queryActivityRepliesByUser(
      this.data.currentUserId,
      this.data.currentPage,
      this.data.pageSize
    ).then(response => {
      console.log('✅ 回复列表加载成功');
      console.log('📊 响应数据:', response);
      
      if (response.status === 'success') {
        const replies = response.data?.replies || [];
        const pagination = response.data?.pagination || {};
        
        console.log('📋 回复数量:', replies.length);
        console.log('📄 分页信息:', pagination);
        
        // 处理回复数据
        const processedReplies = that.processReplyData(replies);
        
        // 如果是下拉刷新，替换列表；否则追加
        let finalList = [];
        if (isPullDown || that.data.currentPage === 1) {
          finalList = processedReplies;
        } else {
          finalList = that.data.replyList.concat(processedReplies);
        }
        
        that.setData({
          replyList: finalList,
          loading: false,
          totalCount: pagination.total || 0,
          hasMore: finalList.length < (pagination.total || 0)
        });
        
        console.log('📱 当前回复总数:', finalList.length);
        
        if (processedReplies.length === 0 && that.data.currentPage === 1) {
          wx.showToast({
            title: '暂无回复消息',
            icon: 'none'
          });
        }
      } else {
        console.log('❌ 回复列表加载失败:', response.message);
        that.setData({ loading: false });
        wx.showToast({
          title: response.message || '加载失败',
          icon: 'none'
        });
      }
    }).catch(error => {
      console.error('❌ 回复列表加载失败:', error);
      that.setData({ loading: false });
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      });
    });
  },

  // 📊 处理回复数据
  processReplyData(replies) {
    return replies.map(reply => {
      return {
        replyId: reply.replyId,
        activityId: reply.activityId,
        activityTitle: reply.activityTitle || '未知活动',
        activityLocation: reply.activityLocation || '',
        activityTime: this.formatTime(reply.activityPublishTime),
        replyContent: reply.replyContent || '',
        replyImages: reply.replyImages || [],
        publisherId: reply.publisherId,
        publisherName: reply.publisherUsername || reply.publisherNickname || '未知用户',
        publisherAvatar: imageUtil.processAvatar(reply.publisherUserAvatarUrl || reply.publisherAvatar),
        publisherSignature: reply.publisherUserSignature || '',
        replyTime: this.formatTime(reply.replyTime || reply.created_at),
        replyTimeRaw: reply.replyTime || reply.created_at,
        likeCount: reply.likeCount || 0,
        parentReplyId: reply.parentReplyId,
        isReply: !!reply.parentReplyId, // 是否是回复的回复
        // 活动用户信息
        activityUserName: reply.activityUserName || '未知',
        activityUserAvatar: imageUtil.processAvatar(reply.activityUserAvatar),
      };
    });
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return '';
    
    try {
      const time = new Date(timeStr);
      const now = new Date();
      const diff = now - time;
      
      // 一天内显示时分
      if (diff < 24 * 60 * 60 * 1000) {
        const hours = time.getHours().toString().padStart(2, '0');
        const minutes = time.getMinutes().toString().padStart(2, '0');
        return `${hours}:${minutes}`;
      }
      
      // 一年内显示月日
      if (diff < 365 * 24 * 60 * 60 * 1000) {
        const month = (time.getMonth() + 1).toString().padStart(2, '0');
        const day = time.getDate().toString().padStart(2, '0');
        return `${month}-${day}`;
      }
      
      // 超过一年显示年月日
      const year = time.getFullYear();
      const month = (time.getMonth() + 1).toString().padStart(2, '0');
      const day = time.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch (e) {
      return '';
    }
  },

  // 点击回复项
  onReplyTap(e) {
    const activityId = e.currentTarget.dataset.activityid;
    const activityTitle = e.currentTarget.dataset.activitytitle;
    
    console.log('👆 点击回复，活动ID:', activityId, '活动标题:', activityTitle);
    
    // 跳转到活动详情页
    wx.navigateTo({
      url: `/pages/activity-detail/index?id=${activityId}`
    });
  },

  // 点击回复者头像
  onPublisherAvatarTap(e) {
    const publisherId = e.currentTarget.dataset.publisherid;
    const publisherName = e.currentTarget.dataset.publishername;
    
    console.log('🖼️ 点击回复者头像:', publisherName, '(ID:', publisherId, ')');
    
    // 跳转到用户主页
    wx.navigateTo({
      url: `/pages/user-home/index?userId=${publisherId}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    console.log('🔄 下拉刷新');
    this.loadReplyList(true);
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 上拉加载更多
  onReachBottom() {
    console.log('📄 触底加载更多');
    
    if (!this.data.hasMore) {
      console.log('⚠️ 没有更多数据了');
      wx.showToast({
        title: '没有更多了',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.loading) {
      console.log('⚠️ 正在加载中');
      return;
    }
    
    // 加载下一页
    this.setData({
      currentPage: this.data.currentPage + 1
    });
    this.loadReplyList(false);
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  },

  onShow() {
    console.log('👀 活动消息回复页面显示');
    
    // 🔔 自动初始化通知组件
    const app = getApp();
    if (app.autoInitNotification) {
      app.autoInitNotification();
    }
  },

  onHide() {
    console.log('👋 活动消息回复页面隐藏');
  },

  onUnload() {
    console.log('💾 活动消息回复页面卸载');
  }
});
